package pdf;

import com.alibaba.excel.EasyExcel;
import excel.ExcelDto;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MeiKeDa {
    public static void main(String[] args) {

        File pdfDirectory = new File("E:\\pdf\\2024.10");
        // 获取目录下的所有PDF文件
        File[] pdfFiles = pdfDirectory.listFiles((dir, name) -> name.toLowerCase().endsWith(".pdf"));
        if (pdfFiles != null) {
            for (File file : pdfFiles) {
                System.out.println("正在处理文件: " + file.getName());
                parseTxt(file, "E:\\pdf\\excel\\2024.10");
                //parsePic(file, "/Users/liangpei/Documents/pdf/");
            }
        } else {
            System.out.println("没有找到 PDF 文件。");
        }
        System.out.println("处理完成。");
    }
    /*public static void main(String[] args) {
        String filePath = "/Users/liangpei/Documents/pdf/（已压缩）报关单202401.pdf";
        parse(new File(filePath), "/Users/liangpei/Documents/pdf/");
    }*/

    public static void parseTxt(File file, String jarPath) {
        //File file = new File(filePath);
        try (PDDocument document = Loader.loadPDF(file)) {
            //获取总页数
            int pageCount = document.getNumberOfPages();
            System.out.println("PDF 总页数：" + pageCount);

            List<ExcelDto> excelDtoList = new ArrayList<ExcelDto>();

            String firstLineData = "";
            //循环读取
            for (int i = 1; i <= pageCount; i++) {
                //获取指定页
                PDFTextStripper stripper = new PDFTextStripper();
                stripper.setStartPage(i);
                stripper.setEndPage(i);
                String text = stripper.getText(document);

                // 提取第一行数据（报关单编号）
                if (i == 1) {
                    Pattern firstLinePattern = Pattern.compile("\\*(\\d+)\\*");
                    Matcher firstLineMatcher = firstLinePattern.matcher(text);
                    if (firstLineMatcher.find()) {
                        firstLineData = firstLineMatcher.group(1);
                        System.out.println("报关单编号: " + firstLineData);
                    }
                }

                // 按行处理文本
                String[] lines = text.split("\\r?\\n");
                for (int j = 0; j < lines.length; j++) {
                    String line = lines[j];

                    if(line.contains("4414909090")){
                        System.out.println(1);
                    }
                    // 检查是否是商品编码行
                    String patternString = "(\\d+)\\D*(\\d{10})([\\p{IsHan}]+)";
                    Pattern productLinePattern = Pattern.compile(patternString);
                    Matcher productLineMatcher = productLinePattern.matcher(line);
                    if (productLineMatcher.find()) {
                        String productCode = productLineMatcher.group(2);
                        if(firstLineData.contains(productCode)){
                            continue;
                        }

                        // 寻找总价和币制
                        int priceIndex = -1; // 通常总价在商品编码行后的第三行
                        int currencyIndex = -1; // 通常币制在商品编码行后的第四行

                        // 从当前行开始查找总价和币制
                        for (int k = j + 1; k < lines.length; k++) {
                            String currentLine = lines[k];

                            // 提取总价
                            Pattern pricePattern = Pattern.compile("(\\d+\\.\\d+)");
                            Matcher priceMatcher = pricePattern.matcher(currentLine);
                            if (priceMatcher.find()) {
                                priceIndex = k;
                                break;
                            }
                        }

                        // 如果找到了总价，继续查找币制
                        if (priceIndex != -1) {
                            for (int k = priceIndex + 1; k < lines.length; k++) {
                                String currentLine = lines[k];

                                // 提取币制
                                Pattern currencyPattern = Pattern.compile("(美元|欧元|人民币|USD)");
                                Matcher currencyMatcher = currencyPattern.matcher(currentLine);

                                if (currencyMatcher.find()) {
                                    currencyIndex = k;
                                    priceIndex = k - 1; // 假设总价在币制行的前一行
                                    break;
                                }
                            }
                        }

                        if (priceIndex != -1 && currencyIndex != -1) {
                            String totalPrice = lines[priceIndex].trim();
                            String currency = lines[currencyIndex].trim();

                            System.out.println("商品编码: " + productCode + ", 总价: " + totalPrice + ", 币制: " + currency);

                            ExcelDto excelDto = new ExcelDto();
                            excelDto.setNo(firstLineData);
                            excelDto.setType(currency);
                            excelDto.setAmount(totalPrice);
                            excelDto.setGoodsNo(productCode);

                            excelDtoList.add(excelDto);
                        }
                    }
                }
            }
            String fileName = file.getName().replace(".pdf", ".xlsx");


            String excelPath = jarPath + File.separator + fileName;
            System.out.println("正在生成 Excel 文件: " + excelPath);
            // 确保目标目录存在
            File excelDir = new File(jarPath );
            if (!excelDir.exists()) {
                boolean mkdirsSuccess = excelDir.mkdirs();
                if (mkdirsSuccess) {
                    //System.out.println("目录创建成功: " + excelDir.getAbsolutePath());
                } else {
                    //System.err.println("目录创建失败: " + excelDir.getAbsolutePath());
                    return;
                }
            }


            EasyExcel.write(new File(excelPath), ExcelDto.class)
                    //.registerWriteHandler(new CustomMergeStrategy(0))
                    .sheet("报关单")
                    .doWrite(excelDtoList);
        } catch (Exception e) {
            System.out.println("处理文件 " + file.getName() + " 出错。");
            e.printStackTrace();
        }
    }
}
